package com.xl.tools;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.HashMap;
import java.util.Map;

public class BikeQrCodeUtils {

    public static void main(String[] args) {
        String url = "https://wx.chargeland.cn/qcode?code=";
        File outDir = new File("D:/guizhou");
        File logoFile = new File("D:/logo.png");
        outDir.mkdirs();
        String qrCodes = "473091100345\n" +
                "473091100561\n" +
                "473091100570\n" +
                "473091100150\n" +
                "473091100666\n" +
                "473091101742\n" +
                "473091101342\n" +
                "473091101924\n" +
                "473091101337\n" +
                "473091100556\n" +
                "473091100343\n" +
                "473091101344\n" +
                "473091101338\n" +
                "473091101434\n" +
                "473091100568\n" +
                "473091102970\n" +
                "473091101512\n" +
                "473091101926\n" +
                "473091100964\n" +
                "473091101143\n" +
                "473091101343\n" +
                "473091100573\n" +
                "473091100158\n" +
                "473091102272\n" +
                "473091100149\n" +
                "473091100569\n" +
                "473091101741\n" +
                "473091101878\n" +
                "473091100140\n" +
                "473091100965\n" +
                "473091101945\n" +
                "473091102274\n" +
                "473091100562\n" +
                "473091101433\n" +
                "473091100515\n" +
                "473091101432\n" +
                "473091102969\n" +
                "473091101946";
        String [] piles = qrCodes.split("\n");
        for(String p : piles){
            System.out.println(p);
            if(p == null || p.trim().isEmpty()){
                continue;
            }
            File pileDir = new File(outDir,p);
            pileDir.mkdirs();
            drawLogoQRCode(logoFile,new File(pileDir,p+".png"),url.concat(p),p);

//            for(int i = 1 ; i <= 10;i++){
//                String gun = String.format("%02d",i);
//                String code = p+"_"+ gun;
//                System.out.println(code);
//                drawLogoQRCode(logoFile,new File(pileDir,code +".png"),url.concat(code),p);
//            }
        }

    }

    public static BufferedImage drawLogoQRCode(File logoFile, File codeFile, String qrUrl, String note) {
        int size = 400;
        BufferedImage image = new BufferedImage(size, size, BufferedImage.TYPE_INT_RGB);
        int QRCOLOR = 0xFF000000; // 默认是黑色
        int BGWHITE = 0xFFFFFFFF; // 背景颜色
        Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>() {
            private static final long serialVersionUID = 1L;

            {
                put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);// 设置QR二维码的纠错级别（H为最高级别）具体级别信息
                put(EncodeHintType.CHARACTER_SET, "utf-8");// 设置编码方式
                put(EncodeHintType.MARGIN, 0);
            }
        };
        try {
            MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
            // 参数顺序分别为：编码内容，编码类型，生成图片宽度，生成图片高度，设置参数
            BitMatrix bm = multiFormatWriter.encode(qrUrl, BarcodeFormat.QR_CODE, size, size, hints);

            // 开始利用二维码数据创建Bitmap图片，分别设为黑（0xFFFFFFFF）白（0xFF000000）两色
            for (int x = 0; x < size; x++) {
                for (int y = 0; y < size; y++) {
                    image.setRGB(x, y, bm.get(x, y) ? QRCOLOR : BGWHITE);
                }
            }

            int width = image.getWidth();
            int height = image.getHeight();
            if (logoFile != null && logoFile.exists()) {
                // 构建绘图对象
                Graphics2D g = image.createGraphics();
                // 读取Logo图片
                BufferedImage logo = ImageIO.read(logoFile);
                // 开始绘制logo图片
                g.drawImage(logo, width * 2 / 5, height * 2 / 5, width * 2 / 10, height * 2 / 10, null);
                g.dispose();
                logo.flush();
            }

            // 自定义文本描述
            if (note != null && !note.trim().isEmpty()) {
                // 新的图片，把带logo的二维码下面加上文字
                BufferedImage outImage = new BufferedImage(400, 445, BufferedImage.TYPE_4BYTE_ABGR);
                Graphics2D outg = outImage.createGraphics();
                // 画二维码到新的面板
                outg.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null);
                // 画文字到新的面板
                outg.setColor(Color.BLACK);
                outg.setFont(new Font("楷体", Font.BOLD, 30)); // 字体、字型、字号
                int strWidth = outg.getFontMetrics().stringWidth(note);
                if (strWidth > 399) {
                    // //长度过长就截取前面部分
                    // 长度过长就换行
                    String note1 = note.substring(0, note.length() / 2);
                    String note2 = note.substring(note.length() / 2, note.length());
                    int strWidth1 = outg.getFontMetrics().stringWidth(note1);
                    int strWidth2 = outg.getFontMetrics().stringWidth(note2);
                    outg.drawString(note1, 200 - strWidth1 / 2, height + (outImage.getHeight() - height) / 2 + 12);
                    BufferedImage outImage2 = new BufferedImage(400, 485, BufferedImage.TYPE_4BYTE_ABGR);
                    Graphics2D outg2 = outImage2.createGraphics();
                    outg2.drawImage(outImage, 0, 0, outImage.getWidth(), outImage.getHeight(), null);
                    outg2.setColor(Color.BLACK);
                    outg2.setFont(new Font("宋体", Font.BOLD, 30)); // 字体、字型、字号
                    outg2.drawString(note2, 200 - strWidth2 / 2, outImage.getHeight() + (outImage2.getHeight() - outImage.getHeight()) / 2 + 5);
                    outg2.dispose();
                    outImage2.flush();
                    outImage = outImage2;
                } else {
                    outg.drawString(note, 200 - strWidth / 2, height + (outImage.getHeight() - height) / 2 + 12); // 画文字
                }
                outg.dispose();
                outImage.flush();
                image = outImage;
            }

            image.flush();
            if (codeFile != null) {
                codeFile.getParentFile().mkdirs();
                ImageIO.write(image, "png", codeFile); // TODO
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return image;
    }

}
